<template>
  <div class="gauge-chart-container flex flex-col">
    <!-- 图表容器 -->
    <div ref="chartContainer" class="chart-container" :style="containerStyle">
      <VueUiGauge
        :config="config"
        :dataset="dataset"
        :key="renderVersion"
        :style="{ width: '100%', height: '100%' }"
      />
    </div>
  </div>
</template>

<script>
import { defineProps, ref, watch, onMounted, onUnmounted, nextTick, computed } from 'vue';
import { VueUiGauge } from "vue-data-ui";
import "vue-data-ui/style.css";

export default {
  name: 'GaugeChart',
  components: { VueUiGauge },
  props: {
    component: {
      type: Object,
      required: true,
      description: '仪表盘组件配置'
    },
    isPreview: {
      type: Boolean,
      default: false,
      description: '是否预览模式'
    }
  },
  setup(props) {
    // 图表容器DOM引用
    const chartContainer = ref(null);
    // 渲染版本号 - 用于强制重绘
    const renderVersion = ref(1);
    // 容器尺寸
    const containerSize = ref({ width: 0, height: 0 });
    // ResizeObserver实例
    let resizeObserver = null;

    // 容器样式 - 确保尺寸正确应用
    const containerStyle = computed(() => ({
      width: '100%',
      height: '100%',
      minWidth: '100px',
      minHeight: '100px'
    }));

    // 图表配置
    const config = ref({
      debug: false,
      loading: false,
      responsive: true,
      theme: '',
      customPalette: [],
      style: {
        fontFamily: 'inherit',
        chart: {
          backgroundColor: props.component.bgColor || '#FFFFFFff',
          color: '#1A1A1Aff',
          animation: {
            use: true,
            speed: 3,
            acceleration: 1
          },
          layout: {
            radiusRatio: 0.8,
            track: {
              size: 1,
              useGradient: true,
              gradientIntensity: 20
            },
            markers: {
              show: true,
              color: '#1A1A1Aff',
              bold: true,
              fontSizeRatio: 1,
              offsetY: 0,
              roundingValue: 0,
              prefix: '',
              suffix: ''
            },
            segmentNames: {
              show: true,
              curved: true,
              offsetRatio: 1.1,
              fontSize: 14,
              minFontSize: 6,
              useSerieColor: true
            },
            pointer: {
              show: true,
              type: 'pointy',
              size: 1,
              useRatingColor: true
            }
          },
          title: {
            text: props.component.title || '',
            color: props.component.titleColor || '#1A1A1Aff',
            fontSize: props.component.titleFontSize || 20,
            bold: true,
            textAlign: 'center'
          }
        }
      },
      userOptions: {
        show: !props.isPreview,
        buttons: {
          pdf: false,
          img: !props.isPreview,
          fullscreen: true
        }
      }
    });

    // 图表数据
    const dataset = ref({
      series: [
        { from: 0, to: 30, color: '#ff4d4f', name: '低' },
        { from: 30, to: 70, color: '#faad14', name: '中' },
        { from: 70, to: 100, color: '#52c41a', name: '高' }
      ],
      value: props.component.value || 60
    });

    // 处理尺寸变化
    const handleResize = async () => {
      if (!chartContainer.value) return;
      
      // 获取容器实际尺寸
      const rect = chartContainer.value.getBoundingClientRect();
      const newWidth = Math.floor(rect.width);
      const newHeight = Math.floor(rect.height);
      
      // 只有尺寸变化明显时才触发重绘
      if (
        Math.abs(newWidth - containerSize.value.width) > 10 ||
        Math.abs(newHeight - containerSize.value.height) > 10
      ) {
        containerSize.value = { width: newWidth, height: newHeight };
        await nextTick();
        renderVersion.value += 1;
        
        // 调试信息
        console.log(`仪表盘尺寸更新: ${newWidth}x${newHeight}`);
      }
    };

    // 初始化尺寸监听
    const initResizeObserver = () => {
      // 清理旧的监听器
      if (resizeObserver) {
        resizeObserver.disconnect();
      }
      
      // 创建新的监听器
      if (window.ResizeObserver) {
        resizeObserver = new ResizeObserver(entries => {
          if (entries.length) {
            handleResize();
          }
        });
        
        // 监听图表容器
        if (chartContainer.value) {
          resizeObserver.observe(chartContainer.value);
        }
      } else {
        // 降级方案：监听窗口resize事件
        window.addEventListener('resize', debouncedHandleResize);
      }
    };

    // 防抖处理，避免频繁触发
    const debouncedHandleResize = (() => {
      let timeout;
      return () => {
        clearTimeout(timeout);
        timeout = setTimeout(handleResize, 100);
      };
    })();

    // 从API加载数据
    const loadDataFromApi = async () => {
      if (props.component.apiUrl) {
        try {
          const response = await fetch(props.component.apiUrl);
          const data = await response.json();
          
          if (typeof data.value !== 'undefined') {
            dataset.value.value = data.value;
          }
          
          if (data.series) {
            dataset.value.series = data.series;
          }
        } catch (error) {
          console.error('加载仪表盘数据失败:', error);
        }
      }
    };

    // 设置定时刷新
    let refreshTimer = null;
    const setupRefreshTimer = () => {
      if (refreshTimer) {
        clearInterval(refreshTimer);
      }
      
      if (props.component.dataSourceType === 'api' && props.component.refreshInterval > 0) {
        refreshTimer = setInterval(loadDataFromApi, props.component.refreshInterval * 1000);
      }
    };

    // 初始化
    onMounted(() => {
      // 初始获取尺寸并绘制
      nextTick().then(() => {
        handleResize();
        initResizeObserver();
        
        // 加载API数据
        if (props.component.dataSourceType === 'api') {
          loadDataFromApi();
          setupRefreshTimer();
        }
      });
    });

    // 清理
    onUnmounted(() => {
      if (refreshTimer) {
        clearInterval(refreshTimer);
      }
      
      if (resizeObserver && chartContainer.value) {
        resizeObserver.unobserve(chartContainer.value);
        resizeObserver.disconnect();
      } else {
        window.removeEventListener('resize', debouncedHandleResize);
      }
    });

    // 监听组件属性变化
    watch(
      () => props.component,
      (newVal) => {
        // 更新标题
        config.value.style.chart.title.text = newVal.title || '';
        config.value.style.chart.title.color = newVal.titleColor || '#1A1A1Aff';
        
        // 更新背景色
        config.value.style.chart.backgroundColor = newVal.bgColor || '#FFFFFFff';
        
        // 更新值
        if (typeof newVal.value !== 'undefined') {
          dataset.value.value = newVal.value;
        }
        
        // 数据源变化时重新加载
        if (newVal.dataSourceType === 'api') {
          loadDataFromApi();
          setupRefreshTimer();
        }
        
        // 配置变化后强制重绘
        handleResize();
      },
      { deep: true }
    );

    return {
      chartContainer,
      config,
      dataset,
      renderVersion,
      containerStyle
    };
  }
};
</script>

<style scoped>
.gauge-chart-container {
  padding: 16px;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  /* 确保父容器能被正确撑开 */
  min-width: 0;
  min-height: 0;
}

.chart-container {
  box-sizing: border-box;
  /* 关键：确保容器能响应父元素尺寸 */
  width: 100%;
  height: 100%;
  position: relative;
}

/* 强制刷新时避免闪烁
::v-deep .vue-ui-gauge {
  transition: all 0.2s ease;
} */
</style>
